<template lang="pug">
.up-warp
    el-upload(
        ref="upload"
        :on-remove="onChange"
        :multiple="multiple"
        :limit="limit"
        :on-exceed="handleExceed"
        :file-list="fileList"
        :auto-upload="false"
        :accept="accept"
        :on-change="onChange"
    )
            template(#trigger)
                el-button(type="primary" class="bcuploadbtn") {{text}}
            template(#tip)
                .text-red {{pop}}
</template>

<script setup>

import { ref } from 'vue'
import { warning } from '@/utils/message'
import { getFileSize } from '@/utils'
const props = defineProps({
    text: {
        type: String,
        default: '选择文件'
    },
    pop: { //提示语
        type: String,
        default: ''
    },
    action: {
        type: String,
        default: ''
    },
    accept: {
        type: String,
        default: ''
    },
    multiple: {
        type: Boolean,
        default: true
    },
    limit: {
        type: Number,
        default: 100
    },
    fileList: {
        type: Array,
        default: function(){
            return []
        }
    },
    size: {
        type: Number,
        default: 2 * 1024 * 1024 * 1024
    }
})
const handleExceed = (data) => {
    warning(`最多同时上传${props.limit}个文件`)
}
const emit = defineEmits(['onChange']) //

const onChange = (data, fileList) => {
    if (fileList.length > 1){
        let num = 0
        fileList.forEach((val) => {
            if (val.name == data.name){
                num++
            }
        })
        if (num > 1){
            warning('上传文件重复')
            fileList.length = fileList.length - 1
            return
        }
    }
    if (props.size){
        if (data.size > props.size){
            warning(`文件大小为${getFileSize(data.size)},超过${props.size / 1024 / 1024 / 1024}G,请压缩分卷上传`)
            fileList.length = fileList.length - 1
            return
        }
    }
    if (props.accept){
        const names = data.name.split('.')
        if (props.accept.indexOf(names[names.length - 1]) == -1){
            fileList.length = fileList.length - 1
            warning('文件格式不正确,格式为：' + props.accept)
            return
        }
    }
    const file = data.raw
    const fileLists = fileList.map((val) => {
        return val.raw || val
    })
    emit('onChange', file, fileLists)

}
</script>

<style lang="less" scoped>
.up-warp{
    margin: 10px 0;
}
.text-red{
    color: red;
    font-size: 12px;
    line-height: 30px;
    margin-left: 5px;
}
</style>